<template>
  <section class="content clear">
    <section class="inner-top">
      <section class="inner-top">
        <span class="detail-back" @click="back">应用管理</span><span style="margin:0px 3px">></span><span>{{appName}}</span>
      </section>
    </section>
    <section class="inner-bottom">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="路由" name="1">
          <el-row :gutter="20">
            <el-col :span="4">
              <el-input type="text" placeholder="输入路由名称" v-model="searchRouterName" clearable></el-input>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchRouterStatus" placeholder="请选择路由状态" size="small" clearable>
                <el-option label="全部" value="-1">
                </el-option>
                <el-option label="已启用" value="1">
                </el-option>
                <el-option label="已禁用" value="0">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-button size="small" type="primary" @click="getRouterByApp('search')">查询</el-button>
            </el-col>
            <el-col :span="12" align="right">
              <el-button size="small" type="primary" @click="addRouter('add')">添加路由</el-button>
            </el-col>
          </el-row>
          <el-table :data="routerTableData" style="width: 100%;margin-top:20px;">
            <el-table-column type="index" label="编号" width="50">
            </el-table-column>
            <el-table-column prop="title" label="名称">
            </el-table-column>
            <el-table-column prop="type" label="类型">
              <template slot-scope="scope">
                {{scope.row.type === 0?'基本路由':'菜单路由'}}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="路由标识">
            </el-table-column>
            <el-table-column prop="path" label="地址">
            </el-table-column>
            <el-table-column prop="icon" label="图标">
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间">
              <template slot-scope="scope">
                {{scope.row.createTime | moment('YYYY-MM-DD HH:mm:ss')}}
              </template>
            </el-table-column>
            <el-table-column prop="enabled" label="状态">
              <template slot-scope="scope">
                {{scope.row.enabled?'已启用':'已禁用'}}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="addResourceToRouter(scope.row)">资源</el-button>
                <!-- <el-button type="text">按钮</el-button> -->
                <el-button type="text" @click="addRouter('edit', scope.row)">编辑</el-button>
                <el-button type="text" @click="delRouter(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="按钮" name="2">
          <el-row :gutter="20">
            <el-col :span="4">
              <el-input type="text" placeholder="输入按钮名称" v-model="searchButtonName" clearable></el-input>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchButtonStatus" placeholder="请选择按钮状态" size="small" clearable>
                <el-option label="全部" value="-1">
                </el-option>
                <el-option label="已启用" value="1">
                </el-option>
                <el-option label="已禁用" value="0">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-button size="small" type="primary" @click="getButtonByApp('search')">查询</el-button>
            </el-col>
            <el-col :span="12" align="right">
              <el-button align="right" size="small" type="primary" @click="addButton('add')">添加按钮</el-button>
            </el-col>
          </el-row>
          <el-table :data="buttonTableData" style="width: 100%;margin-top:20px;">
            <el-table-column type="index" label="编号" width="180">
            </el-table-column>
            <el-table-column prop="name" label="名称" width="180">
            </el-table-column>
            <el-table-column prop="routerName" label="归属路由" width="180">
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间">
              <template slot-scope="scope">
                {{scope.row.createTime | moment('YYYY-MM-DD HH:mm:ss')}}
              </template>
            </el-table-column>
            <el-table-column prop="enabled" label="状态">
              <template slot-scope="scope">
                {{scope.row.enabled ? '启用' : '禁用'}}
              </template>
            </el-table-column>
            <el-table-column prop="address" label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="addResourceToRouter(scope.row)">资源</el-button>
                <el-button type="text" @click="addButton('edit',scope.row)">编辑</el-button>
                <el-button type="text" @click="delButton(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <section class="content-page" style="margin-top:50px;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="activeName==='1'?routerPage.current:buttonPage.current" :page-sizes="[10, 15, 20, 30]" :page-size="activeName==='1'?routerPage.size:buttonPage.size" layout="total, sizes, prev, pager, next, jumper" :total="activeName==='1'?routerPage.total:buttonPage.total">
        </el-pagination>
      </section>
    </section>
    <!-- 新增、编辑路由 -->
    <el-dialog :title="isAddOrEdit === 'add'?'新增路由':'编辑路由'" :visible.sync="routerDialogVisible" width="600px" :before-close="handleClose">
      <el-form label-width="100px" :model="routerFrom" ref="routerFrom" :rules="routerFromRules">
        <el-form-item label="路由类型：" prop="type">
          <el-radio-group v-model="routerFrom.type">
            <el-radio-button :label="0">基本路由</el-radio-button>
            <el-radio-button :label="1">菜单路由</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="路由名称：" prop="title">
          <el-input v-model="routerFrom.title"></el-input>
        </el-form-item>
        <el-form-item label="路由图标：" prop="icon" v-if="routerFrom.type===1">
          <el-input v-model="routerFrom.icon"></el-input>
        </el-form-item>
        <el-form-item label="路由地址：" prop="path">
          <el-input v-model="routerFrom.path"></el-input>
        </el-form-item>
        <el-form-item label="路由标识：" prop="name">
          <el-input v-model="routerFrom.name"></el-input>
        </el-form-item>
        <el-form-item label="是否启用：" prop="enabled">
          <el-radio-group v-model="routerFrom.enabled">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="路由排序：" prop="sort" v-if="routerFrom.type===1">
          <el-input v-model="routerFrom.sort"></el-input>
        </el-form-item>
        <el-form-item label="上级路由：" prop="parentId" v-if="routerFrom.type===1">
          <el-cascader v-model="routerFrom.parentId" :options="routerOptions" :props="{ checkStrictly: true,value: 'id',label: 'title' }" @change="selectParentRouter"></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sureAddRouter('routerFrom')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增、编辑按钮 -->
    <el-dialog :title="isAddOrEdit === 'add'?'新增按钮':'编辑按钮'" :visible.sync="buttonDialogVisible" width="600px" :before-close="handleClose">
      <el-form label-width="100px" :model="buttonFrom" ref="buttonFrom" :rules="buttonFromRules">
        <el-form-item label="按钮名称：" prop="name">
          <el-input v-model="buttonFrom.name"></el-input>
        </el-form-item>
        <el-form-item label="所属路由：" prop="routerId">
          <el-select v-model="buttonFrom.routerId" placeholder="请选择(可输入搜索)" style="width:100%" filterable>
            <el-option v-for="(item,index) in routerListData" :key="index" :label="`${item.title}(${item.name})`" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用：" prop="enabled">
          <el-radio-group v-model="buttonFrom.enabled">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sureAddButton('buttonFrom')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="resourceDialog">
      <transferResource :routerOrButtonId="currentRouterOrButtonId" :type="activeName"></transferResource>
    </el-dialog>
  </section>
</template>
<script>
import transferResource from './components/transferResource'
import {findRouterQueryByRoleQueryUsingPOST, findButtonByButtonQueryUsingPOST, createRouterUsingPOST, updateRouterUsingPUT,
  deleteRouterUsingDELETE, findMenuByRoleIdAndAppIdUsingGET, createButtonUsingPOST, updateButtonUsingPUT, deleteButtonUsingDELETE} from '@api/systemManage'
export default {
  name: 'applicationDetail',
  components: {
    transferResource
  },
  data () {
    return {
      searchRouterName: null,
      searchButtonName: null,
      searchRouterStatus: null,
      searchButtonStatus: null,
      currentAppId: null,
      isAddOrEdit: 'add', // add:新增；edit:编辑应用
      activeName: '1',
      routerTableData: [],
      buttonTableData: [],
      routerListData: [], // 所有路由列表
      routerDialogVisible: false,
      appName: this.$route.query.appName,
      routerFrom: {
        appId: this.$route.query.id,
        type: 0,
        name: null,
        icon: null,
        path: null,
        title: null,
        enabled: null,
        sort: null,
        parentId: -1
      },
      routerFromRules: {
        name: [{required: true, message: '请输入路由名称', trigger: 'blur'}],
        path: [{required: true, message: '请输入路由地址', trigger: 'blur'}],
        title: [{required: true, message: '请输入路由标题', trigger: 'blur'}],
        enabled: [{required: true, message: '请选择是否启用', trigger: 'blur'}]
      },
      routerOptions: [
        {
          id: -1,
          title: '顶层菜单',
          children: []
        }
      ],
      resourceDialog: false,
      currentRouterOrButtonId: null, // 当前正在操作的路由或者按钮id
      transferResourceData: [], // 可用接口
      routerPage: {
        current: 1,
        total: 0,
        size: 10
      },
      buttonPage: {
        current: 1,
        total: 0,
        size: 10
      },
      buttonFrom: {
        appId: null,
        enabled: '0',
        routerId: null,
        name: null
      },
      buttonFromRules: {
        name: [{required: true, message: '请输入按钮名称', trigger: 'blur'}],
        routerId: [{required: true, message: '请选择所属路由', trigger: 'blur'}],
        enabled: [{required: true, message: '请选择是否启用', trigger: 'blur'}]
      },
      buttonDialogVisible: false
    }
  },
  watch: {
    activeName (val) {
      this.initPage()
    }
  },
  created () {
    this.appName = this.$route.query.appName
    this.initPage()
  },
  methods: {
    initPage () {
      this.currentAppId = Number(this.$route.query.id)
      if (this.activeName === '1') {
        this.getRouterByApp()
      } else {
        this.getRouterByApp('2')
        this.getButtonByApp()
      }
      this.getMeauByApp()
    },
    // 获取路由已有的资源
    addResourceToRouter (rowData) {
      this.resourceDialog = true
      this.currentRouterOrButtonId = rowData.id
    },
    // 获取应用路由
    getRouterByApp (type = 'init') {
      // this.currentAppId, this.routerPage.current, this.routerPage.size
      let params = {
        'appId': this.currentAppId,
        'enabled': this.searchRouterStatus === '1' ? true : this.searchRouterStatus === '0' ? false : null,
        'name': this.searchRouterName ? this.searchRouterName : null,
        'page': type === '2' ? 1 : this.routerPage.current, // type=2:表示切换到按钮了；需要获取所有的路由用于添加按钮是选择归属路由
        'size': type === '2' ? 100000 : this.routerPage.size // type=2:表示切换到按钮了；需要获取所有的路由用于添加按钮是选择归属路由
      }
      findRouterQueryByRoleQueryUsingPOST(params).then(res => {
        if (res.status) {
          this.routerTableData = res.data.list
          if (type === '2') {
            this.routerListData = res.data.list
          }
          this.routerPage.total = res.data.total
        }
      })
    },
    // 获取应用按钮
    getButtonByApp (type = 'init') {
      let params = {
        'appId': this.currentAppId,
        'enabled': this.searchButtonStatus === '1' ? true : this.searchButtonStatus === '0' ? false : null,
        'name': this.searchButtonName ? this.searchButtonName : null,
        'page': this.buttonPage.current,
        'size': this.buttonPage.size
      }
      findButtonByButtonQueryUsingPOST(params).then(res => {
        if (res.status) {
          this.buttonTableData = res.data.list
          this.buttonPage.total = res.data.total
        }
      })
    },
    // 获取菜单
    getMeauByApp () {
      findMenuByRoleIdAndAppIdUsingGET(this.currentAppId).then(res => {
        if (res.status) {
          this.routerOptions[0].children = res.data
          console.log(this.routerOptions)
        }
      })
    },
    // 按钮
    addButton (type, rowData = {}) {
      if (type === 'edit') {
        this.buttonFrom = Object.assign({}, rowData, {
          enabled: rowData.enabled ? '1' : '0'
        })
      }
      this.isAddOrEdit = type
      this.buttonDialogVisible = true
    },
    // 添加按钮
    sureAddButton (formName) {
      this.$refs[formName].validate(valid => {
        if (valid && this.isAddOrEdit === 'add') {
          this.creatButton()
        } else if (valid && this.isAddOrEdit === 'edit') {
          this.editButton()
        }
      })
    },
    creatButton () {
      let params = {
        'appId': this.currentAppId,
        'enabled': Boolean(Number(this.buttonFrom.enabled)),
        'name': this.buttonFrom.name,
        'routerId': this.buttonFrom.routerId
      }
      createButtonUsingPOST(params).then(res => {
        if (res.status) {
          this.$message.success('添加成功！')
          this.getButtonByApp()
          this.handleClose()
        }
      })
    },
    editButton () {
      let params = Object.assign({}, this.buttonFrom, {
        'enabled': Boolean(Number(this.buttonFrom.enabled))
      })
      updateButtonUsingPUT(this.buttonFrom.id, params).then(res => {
        if (res.status) {
          this.$message.success('添加成功！')
          this.getButtonByApp()
          this.handleClose()
        }
      })
    },
    // 删除按钮
    delButton (rowData) {
      this.$confirm('此操作将删除该按钮, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteButtonUsingDELETE(rowData.id).then(res => {
          if (res.status) {
            this.$message.success('删除成功')
            this.getButtonByApp()
            this.handleClose()
          }
        })
      }).catch(() => {

      })
    },
    // 创建路由
    addRouter (type, rowData = {}) {
      if (type === 'edit') {
        this.routerFrom = Object.assign({}, rowData, {
          enabled: rowData.enabled ? '1' : '0'
        })
      }
      this.isAddOrEdit = type
      this.routerDialogVisible = true
    },
    sureAddRouter (formName) {
      this.$refs[formName].validate(valid => {
        if (valid && this.isAddOrEdit === 'add') {
          this.creatRouter()
        } else if (valid && this.isAddOrEdit === 'edit') {
          this.editRouter()
        }
      })
    },
    // 创建应用下路由
    creatRouter () {
      let params = {
        'appId': this.routerFrom.appId,
        'enabled': Boolean(Number(this.routerFrom.enabled)),
        'icon': this.routerFrom.icon,
        'name': this.routerFrom.name,
        'parentId': this.routerFrom.parentId,
        'path': this.routerFrom.path,
        'sort': this.routerFrom.sort,
        'title': this.routerFrom.title,
        'type': this.routerFrom.type
        // 'id': 0
        // 'modifier': 'string',
        // 'modifyTime': '2019-11-05T02:28:56.783Z',
        // 'createTime': '2019-11-05T02:28:56.783Z',
        // 'creator': 'string',
        // 'deleted': 'string',
        // 'version': 0
      }
      if (this.routerFrom.type === 0) {
        delete params.icon
        delete params.parentId
        delete params.sort
      }
      createRouterUsingPOST(params).then(res => {
        if (res.status) {
          this.$message.success('添加成功！')
          this.getRouterByApp()
          this.handleClose()
        }
      })
    },
    // 编辑应用下某个路由
    editRouter () {
      let params = Object.assign({}, this.routerFrom, {
        'enabled': Boolean(Number(this.routerFrom.enabled))
      })
      updateRouterUsingPUT(this.routerFrom.id, params).then(res => {
        if (res.status) {
          this.$message.success('修改成功！')
          this.getRouterByApp()
          this.handleClose()
        }
      })
    },
    // 删除路由
    delRouter (rowData) {
      this.$confirm('此操作将删除该路由, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRouterUsingDELETE(rowData.id).then(res => {
          if (res.status) {
            this.$message.success('删除成功')
            this.getRouterByApp()
            this.handleClose()
          }
        })
      }).catch(() => {

      })
    },
    selectParentRouter (val) {
      this.routerFrom.parentId = val[val.length - 1]
    },
    handleClose () {
      if (this.activeName === '1') {
        this.$refs['routerFrom'].resetFields()
        this.$refs['routerFrom'].clearValidate()
      } else {
        this.$refs['buttonFrom'].resetFields()
        this.$refs['buttonFrom'].clearValidate()
      }
      this.routerDialogVisible = false
      this.buttonDialogVisible = false
    },
    back () {
      this.$router.push({name: 'applicationManage'})
    },
    handleClick () {

    },
    handleSizeChange (val) {
      if (this.activeName === '1') {
        this.routerPage.size = val
      } else {
        this.buttonPage.size = val
      }
      this.initPage()
    },
    handleCurrentChange (val) {
      if (this.activeName === '1') {
        this.routerPage.current = val
      } else {
        this.buttonPage.current = val
      }
      this.initPage()
    }
  }
}
</script>
